package cn.stylefeng.guns.modular.basic.service;

import cn.stylefeng.guns.base.pojo.node.ZTreeNode;
import cn.stylefeng.guns.emuns.ArchiveEmun;
import cn.stylefeng.guns.modular.basic.entity.ArchiveBox;
import cn.stylefeng.guns.modular.basic.entity.ArchiveCabinet;
import cn.stylefeng.guns.modular.basic.entity.ArchiveLayer;
import cn.stylefeng.guns.modular.basic.entity.ArchiveRoom;
import cn.stylefeng.guns.sys.modular.system.entity.Dict;
import cn.stylefeng.guns.sys.modular.system.entity.DictType;
import cn.stylefeng.guns.sys.modular.system.mapper.DictTypeMapper;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.guns.tree.LayuiTree;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Triple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ArchiveDictService extends ServiceImpl<DictTypeMapper, DictType> {

    @Autowired
    private DictService dictService;


    public List<ZTreeNode> tree() {
        final QueryWrapper objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("code", ArchiveEmun.ARCHIVE_TYPE.getValue());
        final DictType dictType = this.baseMapper.selectOne(objectQueryWrapper);
        if (dictType == null) {
            throw new ServiceException(500, "未找到ARCHIVE_TYPE字典");
        }
        final Long dictTypeId = dictType.getDictTypeId();
        return this.dictService.dictTreeList(dictTypeId, null);
    }

    //给定父级，查询所有子集
    public List<String> getChildDictWithParent(String value) {
        final Long dictTypeId = getDictTypeId();
        final Dict one = this.dictService.lambdaQuery()
                .eq(Dict::getDictTypeId, dictTypeId)
                .eq(Dict::getCode, value).one();
        if (one == null) {
            return Collections.EMPTY_LIST;
        }
        final Long dictId = one.getDictId();
        final List<Dict> dicts = this.dictService.getBaseMapper().likeParentIds(dictId);
        return dicts.parallelStream().map(Dict::getCode).collect(Collectors.toList());
    }

    //给定子级，查询所有父级
    public Triple<Long,Long,String> getParentDictWithMe(String value) {
        final Long dictTypeId = getDictTypeId();
        final Dict one = this.dictService.lambdaQuery()
                .eq(Dict::getDictTypeId, dictTypeId)
                .eq(Dict::getCode, value).one();
        if (one == null) {
            return null;
        }
        final Long dictId = one.getDictId();
        final String parentIds = one.getParentIds();
        return ImmutableTriple.of(dictId, one.getParentId(), parentIds);
    }

    public List<Dict> listAllArchiveType() {
        final Long dictTypeId = getDictTypeId();

        Dict dictParam = new Dict();
        dictParam.setDictTypeId(dictTypeId);
        final List<Dict> list = this.dictService.list(Wrappers.query(dictParam));
        return list;
    }

    public List<LayuiTree> listTypeDict() {
        final Long dictTypeId = getDictTypeId();

        Dict dictParam = new Dict();
        dictParam.setDictTypeId(dictTypeId);
        final List<Dict> list = this.dictService.list(Wrappers.query(dictParam));

        if (list == null) {
            return null;
        }

        final List<LayuiTree> all = list.parallelStream().map(it -> {
            LayuiTree tree = new LayuiTree();
            tree.setName(it.getName());
            tree.setValue(it.getCode().toString());
            tree.setParentId(it.getParentId().toString());
            tree.setTemp(it.getDictId().toString());
            return tree;
        }).collect(Collectors.toList());

        return buildDictTree("0", all);
    }

    private Long getDictTypeId() {
        DictType param = new DictType();
        param.setCode(ArchiveEmun.ARCHIVE_TYPE.getValue());
        final DictType dictType = this.baseMapper.selectOne(Wrappers.query(param));
        if (dictType == null) {
            throw new ServiceException(500, "未找到ARCHIVE_TYPE字典");
        }
        return dictType.getDictTypeId();
    }

    public List<LayuiTree> buildDictTree(Object startId, List<LayuiTree> all) {

        //rootNodes
        final List<LayuiTree> rootNodes = all.parallelStream().filter(it -> Objects.equals(startId, it.getParentId())).collect(Collectors.toList());
        List built = new ArrayList<>(rootNodes);

        for (LayuiTree rootNode : rootNodes) {
            rootNode.setChildren(buildDictChildren(rootNode.getTemp(), built, all));
        }
        return rootNodes;
    }

    private List<LayuiTree> buildDictChildren(Object parentId, List<LayuiTree> built, List<LayuiTree> all) {
        List<LayuiTree> me = new ArrayList<>();
        for (LayuiTree layuiTree : all) {
            if (built.contains(layuiTree)) {
                continue;
            }

            if (Objects.equals(parentId, layuiTree.getParentId())) {
                built.add(layuiTree);
                me.add(layuiTree);
                layuiTree.setChildren(buildDictChildren(layuiTree.getTemp(), built, all));
            }
        }
        return me;
    }


    @Autowired
    private ArchiveRoomService archiveRoomService;
    @Autowired
    private ArchiveCabinetService archiveCabinetService;
    @Autowired
    private ArchiveLayerService archiveLayerService;
    @Autowired
    private ArchiveBoxService archiveBoxService;

    /**
     * 组装档案室 -》下拉树
     *
     * @return
     */
    public List<LayuiTree> listArchiveRoom() {
        final List<ArchiveRoom> list = this.archiveRoomService.list();
        return list.parallelStream().map(it -> {
            final LayuiTree layuiTree = new LayuiTree();
            layuiTree.setName(it.getMc());
            layuiTree.setValue(it.getId());
            layuiTree.setParentId(null);
            return layuiTree;
        }).collect(Collectors.toList());
    }

    /**
     * 组装档案柜 -》下拉树
     *
     * @return
     */
    public List<LayuiTree> listArchiveCabinet() {
        final List<ArchiveCabinet> list = this.archiveCabinetService.list();
        return list.parallelStream().map(it -> {
            final LayuiTree layuiTree = new LayuiTree();
            layuiTree.setName(it.getMc());
            layuiTree.setValue(it.getId());
            layuiTree.setParentId(it.getSsdasid());
            return layuiTree;
        }).collect(Collectors.toList());
    }

    /**
     * 组装档案层 -》下拉树
     *
     * @return
     */
    public List<LayuiTree> listArchiveLayer() {
        final List<ArchiveLayer> list = this.archiveLayerService.list();
        return list.parallelStream().map(it -> {
            final LayuiTree layuiTree = new LayuiTree();
            layuiTree.setName(it.getMc());
            layuiTree.setValue(it.getId());
            layuiTree.setParentId(it.getSsdagid());
            return layuiTree;
        }).collect(Collectors.toList());
    }

    public List<LayuiTree> listArchiveBox() {
        final List<ArchiveBox> list = this.archiveBoxService.list();
        return list.parallelStream().map(it -> {
            final LayuiTree layuiTree = new LayuiTree();
            layuiTree.setName(it.getMc());
            layuiTree.setValue(it.getId());
            layuiTree.setParentId(it.getSsdagcid());
            return layuiTree;
        }).collect(Collectors.toList());
    }
}
